# pip install DingtalkChatbot
# conda install conda-forge::flask 或者 pip install flask
# /lib/systemd/system/dingtalk_chatbot.service
from dingtalkchatbot.chatbot import DingtalkChatbot
from flask import Flask, jsonify, request

app = Flask(__name__)

# WebHook地址
webhook = 'https://oapi.dingtalk.com/robot/send?access_token=a6e672340fa263a9946570ad13067e278870eec3b6c1ed3c2f4b7917e4256836'
secret = 'SEC447cd69ef6bc872d38d20169bb2bec03340e1ca99d1b545918b6fc327ee4cfea'  # 可选：创建机器人勾选“加签”选项时使用
# 初始化机器人小丁
ding = DingtalkChatbot(webhook, secret=secret)


def send_dingtalk_message(dingtalk):
    if not dingtalk:
        return
    ding_type = dingtalk.get('ding_type')
    if 'start' == ding_type:
        markdown = ('| 项目 | 列 | 任务 | 开始时间 |\n'
                    '| ---- | ---- | ---- | ---- |\n')
        for item in dingtalk.get('dingtalk'):
            markdown += f"| {item['projectName']} | {item['columnName']} | {item['taskName']} | {item['start_at']} |\n"
        msg = 'TooDask 即将有任务开始 ' + str(dingtalk.get('dingtalk')[0].get('start_at'))
    else:
        markdown = ('| 项目 | 列 | 任务 | 结束时间 |\n'
                    '| ---- | ---- | ---- | ---- |\n')
        for item in dingtalk.get('dingtalk'):
            markdown += f"| {item['projectName']} | {item['columnName']} | {item['taskName']} | {item['end_at']} |\n"
        msg = 'TooDask 即将有任务过期' + str(dingtalk.get('dingtalk')[0].get('end_at'))
    # Text消息@所有人，因为 markdown 格式的消息提醒无弹窗，所以先发送文本再发送 markdown
    ding.send_text(msg=msg, is_at_all=True)
    # Markdown消息@所有人
    result = ding.send_markdown(title=msg, text=markdown, is_at_all=True)
    print(result)


# 定义一个简单的 API
@app.route('/dingtalk/sendmsg', methods=['POST'])
def greet():
    print(request.json)
    send_dingtalk_message(request.json)
    return jsonify({'success': 'true'})


if __name__ == '__main__':
    # 对外提供服务，默认在本地主机的5000端口
    app.run(host='0.0.0.0', port=8000)
